package com.hnichr.ump.oauth.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.hnichr.ump.oauth.service.OAuth2Service;
import com.hnichr.ump.oauth.vo.AccessTokenCheckVo;
import com.hnichr.ump.oauth.vo.AccessTokenVo;
import com.hnichr.ump.oauth.vo.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * oauth2相关接口
 *
 * @author chenxingyang
 */
@Service
@Slf4j
public class OAuth2ServiceImpl implements OAuth2Service {

	@Value("${sso.clientId:}")
	private String clientId;

	@Value("${sso.clientSecret:}")
	private String clientSecret;

	@Value("${sso.baseUrl:}")
	private String baseUrl;

	@Value("${sso.redirectUri:}")
	private String redirectUri;

	/**
	 * 获取令牌url
	 */
	private static final String accessTokenUrl = "/access_token?client_id=%s&client_secret=%s&grant_type=authorization_code&code=%s&redirect_uri=%s";

	/**
	 * 刷新令牌url
	 */
	private static final String refreshTokenUrl = "/refresh_token?client_id=%s&client_secret=%s&grant_type=refresh_token&refresh_token=%s";

	/**
	 * 校验令牌的url
	 */
	private static final String checkTokenUrl = "/introspect?access_token=%s";

	/**
	 * 获取用户信息的url
	 */
	private static final String getUserInfoUrl = "/user_info?access_token=%s";

	/**
	 * 获取令牌
	 *
	 * @param code 授权码
	 * @return
	 */
	@Override
	public AccessTokenVo getAccessToken(String code) {
		String url = baseUrl + String.format(accessTokenUrl, clientId, clientSecret, code, redirectUri);
		log.info("getAccessToken url:{}", url);
		String resp = HttpUtil.get(url);
		log.info("getAccessToken resp:{}", resp);
		if (resp.contains("errorCode")) {
			return null;
		}
		return JSONUtil.toBean(resp, AccessTokenVo.class);
	}

	/**
	 * 刷新令牌
	 *
	 * @param refreshToken 刷新令牌
	 * @return
	 */
	@Override
	public AccessTokenVo refreshToken(String refreshToken) {
		String url = String.format(refreshTokenUrl, clientId, clientSecret, refreshToken);
		String resp = HttpUtil.get(baseUrl + url);
		log.info("refreshToken resp:{}", resp);
		if (resp.contains("errorCode")) {
			return null;
		}
		return JSONUtil.toBean(resp, AccessTokenVo.class);
	}

	/**
	 * 校验令牌
	 *
	 * @param accessToken 令牌
	 * @return
	 */
	@Override
	public AccessTokenCheckVo checkToken(String accessToken) {
		String url = String.format(checkTokenUrl, accessToken);
		String resp = HttpUtil.get(baseUrl + url);
		log.info("checkToken resp:{}", resp);
		if (resp.contains("errorCode")) {
			return null;
		}
		return JSONUtil.toBean(resp, AccessTokenCheckVo.class);
	}

	/**
	 * 获取用户信息
	 *
	 * @param accessToken 令牌
	 * @return
	 */
	@Override
	public UserInfoVo getUserInfo(String accessToken) {
		String url = String.format(getUserInfoUrl, accessToken);
		String resp = HttpUtil.get(baseUrl + url);
		log.info("getUserInfo resp:{}", resp);
		if (resp.contains("errorCode")) {
			return null;
		}
		return JSONUtil.toBean(resp, UserInfoVo.class);
	}

}
